<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/7/20
 * Time: 22:02
 */

namespace app\api\controller\v1;
//use app\api\validate\IdCollection;
use app\lib\exception\ProductException;
use app\lib\exception\RecentException;
use think\Controller;
use app\api\model\Product as ProductModel;

class Product extends Controller
{
    public function getRecent($count = 15)
    {
        $validate = Validate('RecentCount') -> check(['count' => $count]);
        if(!$validate) return Validate('RecentCount') -> getError();
        $result = Model('Product') -> getMostRecent($count);
        $result = collection($result) -> hidden(['summary']);
        if($result -> isEmpty()) throw new RecentException();
        return $result;
    }
    //获取一个商品的信息
    public function getOne($id = '')
    {
        $validate = Validate('IdCollection') -> check(['id' => $id]);
        if(!$validate) throw new ProductException();
        return ProductModel::getOneProduct($id);
    }
    //获得分类下的商品
    public function getCategoryProducts($id = '')
    {
        $validate = Validate('IdCollection') -> check(['id' => $id]);
        if(!$validate) return Validate('IdCollection') -> getError();
        $category = Model('product') -> getCategoryProducts($id);
        if(collection($category) -> isEmpty()) throw new ProductException();
        //转换成数据集，隐藏部分字段
        $category = collection($category) -> hidden(['summary']);
        return $category;
    }
}